<script setup>
import { onMounted, ref } from "vue";
import {
  queryUserPageApi,
  addUserApi,
  getUserByIdApi,
  updateUserApi,
  deleteUserApi,
  batchDeleteUserApi,
  uploadImageApi,
} from "@/api/user";
import { getAllDeptsApi } from "@/api/dept";
import { getAllRolesApi } from "@/api/roles";
import { ElMessage } from "element-plus";
import { ElMessageBox } from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Edit,
  Upload,
} from "@element-plus/icons-vue";

const token = ref("");

// 查询参数
const queryParams = ref({
  name: "",
  phone: "",
  deptId: "",
  status: "",
  page: 1,
  pageSize: 10,
});

// 表格数据
const userList = ref([]);
const total = ref(0);

// 部门列表
const deptList = ref([]);

// 角色列表
const roleList = ref([]);

// 选中的用户ID列表
const selectedUserIds = ref([]);

// 头像上传相关
const avatarUrl = ref("");
const uploadRef = ref(null);

// 搜索
const search = async () => {
  try {
    const result = await queryUserPageApi(queryParams.value);
    if (result.code == 1) {
      userList.value = result.data.rows;
      total.value = result.data.total;
    } else {
      ElMessage.error(result.msg || result.message || "查询失败");
    }
  } catch (error) {
    console.error("查询失败:", error);
    ElMessage.error("查询失败，请稍后重试");
  }
};

// 清空
const clear = () => {
  queryParams.value = {
    name: "",
    phone: "",
    deptId: "",
    status: "",
    page: 1,
    pageSize: 10,
  };
  search();
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  queryParams.value.page = 1;
  search();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.page = val;
  search();
};

// 表格选择
const handleSelectionChange = (selection) => {
  selectedUserIds.value = selection.map((item) => item.id);
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedUserIds.value.length === 0) {
    ElMessage.warning("请选择要删除的用户");
    return;
  }

  ElMessageBox.confirm("确定要删除选中的用户吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const result = await batchDeleteUserApi(selectedUserIds.value);
        if (result.code == 1) {
          ElMessage.success("删除成功");
          search();
        } else {
          ElMessage.error(result.msg || result.message || "删除失败");
        }
      } catch (error) {
        console.error("批量删除失败:", error);
        ElMessage.error("删除失败，请稍后重试");
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

// 获取部门列表
const getDeptList = async () => {
  try {
    const result = await getAllDeptsApi();
    if (result.code == 1) {
      deptList.value = result.data;
    } else {
      console.error("获取部门列表失败:", result.msg || result.message);
    }
  } catch (error) {
    console.error("获取部门列表失败:", error);
  }
};

// 获取角色列表
const getRoleList = async () => {
  try {
    const result = await getAllRolesApi();
    if (result.code == 1) {
      roleList.value = result.data;
    } else {
      console.error("获取角色列表失败:", result.msg || result.message);
    }
  } catch (error) {
    console.error("获取角色列表失败:", error);
  }
};

// 添加用户
const dialogFormVisible = ref(false);
const titleUser = ref("");
const addUser = () => {
  userData.value = {
    name: "",
    username: "",
    phone: "",
    email: "",
    gender: "",
    status: "",
    deptId: "",
    roleId: "",
    remark: "",
    image: "",
  };
  avatarUrl.value = "";
  dialogFormVisible.value = true;
  titleUser.value = "新增用户";
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
};

const userData = ref({
  name: "",
  username: "",
  phone: "",
  email: "",
  gender: "",
  status: "",
  deptId: "",
  roleId: "",
  remark: "",
  image: "",
});

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/jpg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("头像只能是 PNG/JPG/JPEG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("头像大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 头像上传成功
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code === 1) {
    avatarUrl.value = response.data;
    userData.value.image = response.data;
    ElMessage.success("头像上传成功");
  } else {
    ElMessage.error(response.msg || "头像上传失败");
  }
};

// 头像上传失败
const handleAvatarError = () => {
  ElMessage.error("头像上传失败");
};

// 保存用户
const saveUser = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let result;
        if (userData.value.id) {
          result = await updateUserApi(userData.value);
        } else {
          result = await addUserApi(userData.value);
        }
        if (result.code == 1) {
          ElMessage.success("保存成功");
          dialogFormVisible.value = false;
          search();
        } else {
          ElMessage.error(result.msg || result.message || "保存失败");
        }
      } catch (error) {
        console.error("保存失败:", error);
        ElMessage.error("保存失败，请稍后重试");
      }
    } else {
      ElMessage.error("请填写正确的信息");
    }
  });
};

// 表单校验规则 - 根据需求文档更新
const userFormRef = ref(null);
const rules = ref({
  username: [
    { required: true, message: "用户名为必填项", trigger: "blur" },
    { min: 2, max: 20, message: "用户名应该在2-20位之间", trigger: "blur" },
  ],
  name: [
    { required: true, message: "姓名为必填项", trigger: "blur" },
    { min: 2, max: 20, message: "姓名应该在2-20位之间", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "手机号为必填项", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "邮箱为必填项", trigger: "blur" },
    { min: 5, max: 50, message: "邮箱应该在5-50位之间", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
  gender: [{ required: true, message: "性别为必填项", trigger: "change" }],
  status: [{ required: true, message: "状态为必填项", trigger: "change" }],
  remark: [{ max: 200, message: "备注不能超过200个字符", trigger: "blur" }],
});

// 修改用户查询回显
const handleEditFind = async (id) => {
  try {
    const result = await getUserByIdApi(id);
    if (result.code == 1) {
      userData.value = result.data;
      avatarUrl.value = result.data.image || "";
      dialogFormVisible.value = true;
      titleUser.value = "修改用户";
    } else {
      ElMessage.error(result.msg || result.message || "获取用户信息失败");
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取用户信息失败，请稍后重试");
  }
};

// 删除用户
const handleDelete = (id) => {
  ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const result = await deleteUserApi(id);
        if (result.code == 1) {
          ElMessage.success("删除成功");
          search();
        } else {
          ElMessage.error(result.msg || result.message || "删除失败");
        }
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败，请稍后重试");
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

onMounted(() => {
  search();
  getDeptList();
  getRoleList();
  token.value = localStorage.getItem("token");
});
</script>

<template>
  <div class="user-management">
    <!-- 搜索区域 -->
    <el-form
      :inline="true"
      :model="queryParams"
      ref="queryForm"
      class="search-form"
    >
      <el-form-item label="姓名">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="部门">
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="dept in deptList"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          clearable
          style="width: 100%"
        >
          <el-option label="正常" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item class="search-buttons">
        <el-button type="primary" @click="search">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button @click="clear">
          <el-icon><Refresh /></el-icon>清空
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="addUser">
        <el-icon><Plus /></el-icon>添加用户
      </el-button>
      <el-button @click="handleBatchDelete" type="danger">
        <el-icon><Delete /></el-icon>批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="userList"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column prop="name" label="姓名" width="150" align="center" />
      <el-table-column
        prop="username"
        label="用户名"
        width="200"
        align="center"
      />
      <el-table-column label="头像" width="80" align="center">
        <template #default="scope">
          <el-avatar :size="40" :src="scope.row.image" />
        </template>
      </el-table-column>
      <el-table-column
        prop="deptName"
        label="部门"
        width="150"
        align="center"
      />
      <el-table-column
        prop="roleName"
        label="角色"
        width="150"
        align="center"
      />
      <el-table-column prop="phone" label="手机号" width="150" align="center" />
      <el-table-column prop="status" label="状态" width="80" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? "正常" : "停用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="最后操作时间"
        width="180"
        align="center"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleEditFind(scope.row.id)">
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 40, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/修改用户对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="titleUser" width="900">
      <el-form
        :model="userData"
        :rules="rules"
        ref="userFormRef"
        label-width="80px"
      >
        <div class="form-row">
          <div class="form-column">
            <el-form-item label="用户名" prop="username" required>
              <el-input
                v-model="userData.username"
                placeholder="请输入用户名"
              />
            </el-form-item>
            <el-form-item label="手机号" prop="phone" required>
              <el-input v-model="userData.phone" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="性别" prop="gender" required>
              <el-select
                v-model="userData.gender"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="部门" prop="deptId">
              <el-select
                v-model="userData.deptId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="dept in deptList"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="头像" prop="image">
              <div class="avatar-upload-container">
                <el-upload
                  class="avatar-uploader"
                  action="/api/upload"
                  name="image"
                  :headers="{ token: token }"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :on-error="handleAvatarError"
                  ref="uploadRef"
                >
                  <img v-if="avatarUrl" :src="avatarUrl" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"
                    ><Upload
                  /></el-icon>
                </el-upload>
                <div class="upload-tips">
                  <p>图片上传,支持扩展名: .png/.jpg/.jpeg</p>
                  <p>大小限制: 2M</p>
                </div>
              </div>
            </el-form-item>
          </div>
          <div class="form-column">
            <el-form-item label="姓名" prop="name" required>
              <el-input v-model="userData.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email" required>
              <el-input v-model="userData.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="状态" prop="status" required>
              <el-select
                v-model="userData.status"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="正常" :value="1" />
                <el-option label="停用" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
              <el-select
                v-model="userData.roleId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="role in roleList"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
                />
              </el-select>
            </el-form-item>
          </div>
        </div>
        <el-form-item label="备注说明" prop="remark">
          <el-input
            v-model="userData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入用户的备注信息,最多200字"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #fff;
  min-height: 100%;
  border-radius: 8px;
}

.operation-area {
  margin: 20px 0;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.search-form :deep(.el-form-item) {
  margin-right: 20px;
  min-width: 200px;
}

.search-buttons {
  margin-left: auto !important;
  min-width: auto !important;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button .el-icon) {
  margin-right: 4px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}

.avatar-upload-container {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 70px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 18px;
  color: #8c939d;
  width: 70px;
  height: 70px;
  line-height: 70px;
  text-align: center;
}

.avatar {
  width: 70px;
  height: 70px;
  display: block;
  object-fit: cover;
}

.upload-tips {
  flex: 1;
  color: #666;
  font-size: 11px;
  line-height: 1.5;
  min-width: 0;
}

.upload-tips p {
  margin: 3px 0;
}

/* 必填项标记样式 */
:deep(.el-form-item__label) {
  color: #333;
}

/* 确保必填项星号显示为红色 */
:deep(.el-form-item.is-required .el-form-item__label:before) {
  color: #f56c6c;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 20px 20px 15px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 15px 20px 20px;
}

/* 双列布局样式 */
.form-row {
  display: flex;
  gap: 40px;
  margin-bottom: 20px;
}

.form-column {
  flex: 1;
  min-width: 0;
}

.form-column .el-form-item {
  margin-bottom: 18px;
}

.form-column .el-form-item:last-child {
  margin-bottom: 0;
}

/* 备注字段样式 */
.form-row + .el-form-item {
  margin-top: 15px;
}
</style>
